#pragma once

#include "worker.h"
#include "db_wrapper.h"

#include <QWidget>
#include <QDebug>
#include <QThread>
#include <QPushButton>
#include <QVBoxLayout>

#include <functional>

class async_db_reader_tester
        : public QWidget
{
    Q_OBJECT

public:

    async_db_reader_tester(QWidget *parent = nullptr)
        : QWidget(parent)
        , db_wrapper_(new db_wrapper("QMYSQL", "192.9.240.233", "vintik", "qazse", "PIVP_ANI"))
        , btn_       (new QPushButton("start"))
    {
        auto layout = new QVBoxLayout();
        layout->addWidget(btn_);
        layout->addWidget(new QPushButton("I'm not hang"));

        setLayout(layout);

        connect(btn_, SIGNAL(clicked()), this, SLOT(read()));
    }

private Q_SLOTS:
    void read()
    {
        QThread *thread = new QThread;

        auto getter = [this] (int id1, int) { v_.push_back(id1); };
        worker *w = new worker([this, getter] () { load_sectors(db_wrapper_, getter); });

        w->moveToThread(thread);

        // connect(w, SIGNAL(error(QString)), this, SLOT(errorString(QString)));

        connect(thread, SIGNAL(started()), w, SLOT(do_work()));
        connect(w, SIGNAL(finished()), thread, SLOT(quit()));

        connect(w, SIGNAL(finished()), this, SLOT(print_results()));

        connect(w, SIGNAL(finished()), w, SLOT(deleteLater()));
        connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));

        thread->start();
    }

    void print_results()
    {
        for(auto it : v_)
            qDebug() << it;
    }

private:
    std::vector<int> v_;
    db_wrapper       *db_wrapper_;
    QPushButton      *btn_;
};
